package com.example.shirodemo.authentication;

import com.example.shirodemo.properties.ShiroProperties;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.pam.AllSuccessfulStrategy;
import org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy;
import org.apache.shiro.authc.pam.FirstSuccessfulStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.mgt.SubjectDAO;
import org.apache.shiro.session.SessionListener;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.authc.AnonymousFilter;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Base64Utils;

import javax.servlet.Filter;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * ShiroConfig 配置类
 */
@Configuration
public class ShiroConfig {
    @Autowired
    ShiroProperties shiroProperties;

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.password:}")
    private String password;
    @Value("${spring.redis.timeout}")
    private int timeout;
    @Value("${spring.redis.database:0}")
    private int database;

    /**
     * JWT过滤器名称
     */
    private static final String JWT_FILTER_NAME = "jwtFilter";

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        // 设置 securityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // 登录的 url
//        shiroFilterFactoryBean.setLoginUrl(shiroProperties.getLoginUrl());
        // 登录成功后跳转的 url
//        shiroFilterFactoryBean.setSuccessUrl(shiroProperties.getSuccessUrl());
        // 未授权 url
        // (无效果 原因：https://blog.csdn.net/bicheng4769/article/details/86680955?utm_medium=distribute.pc_relevant.none-task-blog-searchFromBaidu-2.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-searchFromBaidu-2.control)
        // 解决方式：全局异常绑定
//        shiroFilterFactoryBean.setUnauthorizedUrl(shiroProperties.getUnauthorizedUrl());

        // 添加自己的过滤器
        Map<String, Filter> filterMap = new LinkedHashMap<>();
        // 配置过滤器 对 『anon』不进行拦截 AnonymousFilter 放行请求 ，设置我们自定义的JWT过滤器
        filterMap.put("anon", new AnonymousFilter());
        filterMap.put(JWT_FILTER_NAME, new JwtFilter());
        shiroFilterFactoryBean.setFilters(filterMap);

        //指定路径和过滤器的对应关系
        LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        // 设置免认证 url
        String[] anonUrls = StringUtils.split(shiroProperties.getAnonUrl(), ",");
        for (String url : anonUrls) {
            filterChainDefinitionMap.put(url, "anon");
        }
        // 配置退出过滤器，其中具体的退出代码 Shiro已经替我们实现了
//        filterChainDefinitionMap.put(shiroProperties.getLogoutUrl(), "logout");

        // 除上以外所有 url都必须认证通过才可以访问，未通过认证自动访问 LoginUrl
//        filterChainDefinitionMap.put("/**", "user");

        // 除上以外所有 url都必须自定义过滤器
        filterChainDefinitionMap.put("/**", JWT_FILTER_NAME);

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

    /**
     * 解决JwtFilter问题
     * - 不要把JwtFilter交由Spring管理，直接new一个实例，交由ShiroFilterFactoryBean管理。
     * 这样可以保证JwtFilter和ShiroFilter的父子关系，保证filter调用链的正确性
     * 但是这样的话，在JwtFilter中就不能进行依赖注入，只能获取applicationContext来获取对应的bean，比较麻烦
     * <p>
     * - 依然把JwtFilter交由Spring管理，但是设置这个bean不要注册到filter调用链中
     *
     * @param jwtFilter
     * @return
     */
    @Bean
    public FilterRegistrationBean registerJwtFilter(@Autowired JwtFilter jwtFilter) {
        // 设置jwt filter不自动注册到spring管理的监听器中，防止与shiro filter同级，导致该监听器必定执行
        FilterRegistrationBean<JwtFilter> jwtFilterRegister = new FilterRegistrationBean<>(jwtFilter);
        jwtFilterRegister.setEnabled(false);

        return jwtFilterRegister;
    }

    @Bean
    public DefaultSessionStorageEvaluator sessionStorageEvaluator() {
        DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
        defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
        return defaultSessionStorageEvaluator;
    }

    @Bean
    public DefaultSubjectDAO subjectDAO() {
        DefaultSubjectDAO defaultSubjectDAO = new DefaultSubjectDAO();
        defaultSubjectDAO.setSessionStorageEvaluator(sessionStorageEvaluator());
        return defaultSubjectDAO;
    }

    @Bean
    public SecurityManager securityManager(DBShiroRealm dbShiroRealm, JwtShiroRealm jwtShiroRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();


        // 设置SecurityManager对象的认证策略，并使用注册自定义MyModularRealmAuthenticator，解决多realm异常覆盖问题
        /*
        三种策略
        1. FirstSuccessfulStrategy：只要有一个Realm验证成功即可，只返回第一个Realm身份验证 成功的认证信息，其他的忽略；
        2. AtLeastOneSuccessfulStrategy：只要有一个Realm验证成功即可，和FirstSuccessfulStrategy 不同，返回所有 Realm 身份验证成功的认证信息（默认）；
        3. AllSuccessfulStrategy：所有Realm验证成功才算成功，且返回所有Realm身份验证成功的 认证信息，如果有一个失败就失败了。
         */
        MyModularRealmAuthenticator myModularRealmAuthenticator = new MyModularRealmAuthenticator();
        myModularRealmAuthenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy());
        securityManager.setAuthenticator(myModularRealmAuthenticator);

        // 配置 SecurityManager，并注入shiroRealm，设置两个Realm，一个用于用户登录验证和访问权限获取；一个用于jwt token的认证
        securityManager.setRealms(Arrays.asList(dbShiroRealm, jwtShiroRealm));

        // 禁用session
        securityManager.setSubjectDAO(subjectDAO());

//        // 配置 shiro session管理器
//        securityManager.setSessionManager(sessionManager());
//        // 配置 缓存管理类 cacheManager 用户缓存用户角色和权限
//        securityManager.setCacheManager(cacheManager());
//        // 配置 rememberMeCookie
//        securityManager.setRememberMeManager(rememberMeManager());
        return securityManager;
    }

    /**
     * cookie管理对象
     *
     * @return
     */
    private CookieRememberMeManager rememberMeManager() {
        CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
        cookieRememberMeManager.setCookie(rememberMeCookie());
        // rememberMe cookie 加密的密钥
        String encryptKey = "shiro_key";
        byte[] encryptKeyBytes = encryptKey.getBytes(StandardCharsets.UTF_8);
        String rememberKey = Base64Utils.encodeToString(Arrays.copyOf(encryptKeyBytes, 16));
        cookieRememberMeManager.setCipherKey(Base64.decode(rememberKey));
        return cookieRememberMeManager;
    }

    /**
     * 效果是重开浏览器后无需重新登录
     *
     * @return
     */
    private SimpleCookie rememberMeCookie() {
        // 设置 cookie 名称，对应 login.html 页面的 <input type="checkbox" name="rememberMe"/>
        SimpleCookie cookie = new SimpleCookie("rememberMe");
        // 设置 cookie 的过期时间，单位为秒，这里为一天
        cookie.setMaxAge(shiroProperties.getCookieTimeout());
        return cookie;
    }

    /**
     * shiro 中配置 redis 缓存
     *
     * @return RedisManager
     */
    private RedisManager redisManager() {
        RedisManager redisManager = new RedisManager();
        redisManager.setHost(host + ":" + port);
        if (StringUtils.isNotBlank(password))
            redisManager.setPassword(password);
        redisManager.setTimeout(timeout);
        redisManager.setDatabase(database);
        return redisManager;
    }

    private RedisCacheManager cacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(redisManager());
        return redisCacheManager;
    }

    @Bean
    public RedisSessionDAO redisSessionDAO() {
        RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
        redisSessionDAO.setRedisManager(redisManager());
        return redisSessionDAO;
    }

    /**
     * session 管理对象
     *
     * @return DefaultWebSessionManager
     */
    @Bean
    public DefaultWebSessionManager sessionManager() {
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();

        Collection<SessionListener> listeners = new ArrayList<>();
        listeners.add(new ShiroSessionListener());
        // 设置 session超时时间
        sessionManager.setGlobalSessionTimeout(shiroProperties.getSessionTimeout() * 1000L);
        sessionManager.setSessionListeners(listeners);
        // 设置session持久化
        sessionManager.setSessionDAO(redisSessionDAO());
        // 去掉shiro登录时url里的JSESSIONID
        sessionManager.setSessionIdUrlRewritingEnabled(false);

        return sessionManager;
    }

    /**
     * 开启使用注解进行权限验证
     *
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor
                = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
}
